#!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
"""Program an FPGA with a bitstream
"""
import argparse
import os
import subprocess
import sys


def program_bitstream_with_vivado(part, bitstream, hw_server_url, hw_target, jtag_freq):
    tcl_file = os.path.join(os.path.dirname(__file__), 'vivado_pgm.tcl')
    if not os.path.isfile(tcl_file):
        raise FileNotFoundError('{} not found.'.format(tcl_file))

    cmd_env = os.environ.copy()
    if hw_server_url is not None:
        cmd_env['HW_SERVER_URL'] = hw_server_url
    if hw_target is not None:
        cmd_env['HW_TARGET'] = hw_target
    if jtag_freq is not None:
        cmd_env['JTAG_FREQ'] = jtag_freq

    cmd = [
        'vivado', '-quiet', '-nolog', '-notrace', '-mode', 'batch', '-source',
        str(tcl_file), '-tclargs', part, bitstream
    ]
    try:
        subprocess.run(cmd, check=True, env=cmd_env)
    except FileNotFoundError as e:
        print("Unable to run Vivado: %s. Is Vivado in your PATH?" % str(e),
              file=sys.stderr)
        return 1
    except subprocess.CalledProcessError as e:
        print(str(e), file=sys.stderr)
        return 1


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--hw-server-url',
                        required=False,
                        default=None,
                        help='The URL of a running Xilinx hardware server to '
                        'connect to. If not specified, a hardware server will '
                        'be started automatically on localhost.')
    parser.add_argument('--hw-target',
                        '-t',
                        required=False,
                        default=None,
                        help='Hardware target to use. Use the TCL command '
                        'get_hw_targets in Vivado to get a list of available '
                        'targets.')
    parser.add_argument('--jtag-freq',
                        '-f',
                        required=False,
                        default=None,
                        help='JTAG frequency (in Hz)')
    parser.add_argument('part', help='Device (part) to flash')
    parser.add_argument('bitstream', help='Path to the bitstream file')
    args = parser.parse_args()

    return program_bitstream_with_vivado(args.part,
                                         args.bitstream,
                                         hw_server_url=args.hw_server_url,
                                         hw_target=args.hw_target,
                                         jtag_freq=args.jtag_freq)


if __name__ == "__main__":
    sys.exit(main())
